<template>
  <div class="public_height100 p20 pub_bgColorFFF">
    <div class="crumbs flex_start">
      <span class="crumbs_active" @click="goPage('layout/orderManagement')">订单管理</span>
      <img src="@/assets/img/customer/crumbs_next.png" alt="返回" class="pub_imgSize16 ml8" />
      <span class="ml8">{{ crumbsTitle }}</span>
    </div>
    <!-- ====== 表格上方的筛选条件 start ======-->
    <div class="table_filter flex_center_columnStart mt20">
      <div class="table_filter_title">订单信息</div>
      <div class="flex_start mt20 pub_width100">
        <div class="table_filter_search flex_start pub_width100">
          <el-form label-width="6rem" :inline="true">
            <el-form-item label="订单日期">
              <el-date-picker v-model="params.dateInput" size="small" type="date" placeholder="请选择订单日期" class="pub_date_picker" :disabled="sourceType == 3"> </el-date-picker>
            </el-form-item>
            <el-form-item>
              <template #label>
                <span>
                  <span>订单类型</span>
                  <el-tooltip placement="top" effect="dark">
                    <div slot="content">
                      <div>一.创建订单时可以选择多个产品，但到订单列表里会按产品数量拆成多个订单；</div>
                      <div>二.若手误创建错了库存，可以创建对冲订单，原价出库平仓；</div>
                      <div>三.创建对冲订单，将会在订单中创建一条订单，期客户信息皆为对冲订单</div>
                    </div>
                    <i class="el-icon-question" style="color:#606266;cursor:help;" />
                  </el-tooltip>
                </span>
              </template>
              <div class="flex_start">
                <div class="flex_start orderType" @click="selectedOrderType(2)">
                  <img v-if="params.isHedging === '2'" class="public_singImg" src="@/assets/img/orderManagement/checked_icon.png" />
                  <img v-else class="public_singImg" src="@/assets/img/orderManagement/unchecked_icon.png" />
                  <span class="ml5">正常订单</span>
                </div>
                <div class="flex_start ml10 orderType" @click="selectedOrderType(1)">
                  <img v-if="params.isHedging === '1'" class="public_singImg" src="@/assets/img/orderManagement/checked_icon.png" />
                  <img v-else class="public_singImg" src="@/assets/img/orderManagement/unchecked_icon.png" />
                  <span class="ml5">对冲订单</span>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <div class="table_filter flex_space_between ">
      <div class="flex_start">
        <div class="table_filter_title">客户信息</div>
      </div>
      <div v-if="sourceType != 3" class="flex_start flex_end">
        <div>
          <el-button type="text" class="w108 pub_button pub_buttonGreen" @click="goPage('layout/chooseCustomer')">
            <img src="@/assets/img/orderManagement/add.png" alt="选择客户" />
            <span class="ml5">{{ customerInfoTable.length > 0 ? '修改客户' : '选择客户' }}</span>
          </el-button>
        </div>
      </div>
    </div>
    <div class="pub_table mt16">
      <ul v-if="customerInfoTable.length > 0" class="flex_start customerInfo">
        <li>
          <span>客户名称:</span><span>{{ customerInfoTable[0].customerName }}</span>
        </li>
        <li>
          <span>课题组:</span><span>{{ customerInfoTable[0].researchGroupName }}</span>
        </li>
        <li>
          <span>采购人:</span><span>{{ customerInfoTable[0].customerPurchaserName }}</span>
        </li>
        <li>
          <span>采购人电话:</span><span>{{ customerInfoTable[0].customerPurchaserPhone }}</span>
        </li>
      </ul>
    </div>
    <div class="table_filter flex_space_between mt34">
      <div class="flex_start">
        <div class="table_filter_title">
          商品信息<el-tooltip placement="top" effect="dark">
            <div slot="content">
              <div>一.因涉及到库存的出入库，库存无法删除和减少，只能增加；</div>
              <div>二.进入编辑订单详情，会把创建订单时关联的产品一并显示出来；</div>
            </div>
            <i class="el-icon-question" style="color:#606266;cursor:help;" />
          </el-tooltip>
        </div>
      </div>
      <div v-if="sourceType == 1" class="flex_start flex_end">
        <el-button type="text" class="w108 pub_button pub_buttonGreen" @click="goPage('layout/stockList')">
          <img src="@/assets/img/orderManagement/add.png" alt="选择客户" />
          <span class="ml5">选择商品</span>
        </el-button>
      </div>
    </div>
    <el-table size="small" :data="productList" border tooltip-effect="dark" class="wp100 mt10">
      <el-table-column type="index" :width="`${70 * $f}`" label="序号" align="center" />
      <el-table-column label="库存编码" show-overflow-tooltip prop="productBatchNo" :min-width="`${150 * $f}`" align="center" />
      <el-table-column label="产品名称" show-overflow-tooltip prop="productBrandArticleNoName" :min-width="`${150 * $f}`" align="center" />
      <el-table-column label="业务员" show-overflow-tooltip :width="`${150 * $f}`" align="center">
        <template slot-scope="{ row }">
          {{ row.companySaleName || '--' }}
        </template>
      </el-table-column>
      <el-table-column label="出货数量" show-overflow-tooltip :width="`${120 * $f}`" align="center">
        <template slot-scope="{ row }">
          {{ row.qty || '--' }}
        </template>
      </el-table-column>
      <el-table-column label="出货单价" show-overflow-tooltip :width="`${120 * $f}`" align="center">
        <template slot-scope="{ row }">
          {{ row.customerSinglePrice || '--' }}
        </template>
      </el-table-column>
      <el-table-column v-if="sourceType === '1'" label="库存数量" show-overflow-tooltip :width="`${100 * $f}`" align="center">
        <template slot-scope="{ row }">
          {{ Number(row.qtyNum).toFixed(0) }}
        </template>
      </el-table-column>
      <el-table-column v-if="sourceType === '1'" label="库存单价" show-overflow-tooltip prop="singlePrice" :width="`${100 * $f}`" align="center" />
      <el-table-column v-if="sourceType === '2'" label="库存单价" show-overflow-tooltip prop="purchaseSinglePrice" :width="`${100 * $f}`" align="center" />
      <el-table-column label="公司名称" show-overflow-tooltip prop="companyName" :min-width="`${150 * $f}`" align="center" />
      <el-table-column label="供应商" show-overflow-tooltip prop="productSupplierName" :width="`${200 * $f}`" align="center" />
      <el-table-column label="品牌" show-overflow-tooltip prop="productBrandName" :width="`${200 * $f}`" align="center" />
      <el-table-column label="货号" show-overflow-tooltip prop="productBrandArticleNo" :width="`${200 * $f}`" align="center" />
      <el-table-column label="单位" show-overflow-tooltip prop="unit" :width="`${70 * $f}`" align="center" />
      <el-table-column label="规格" show-overflow-tooltip prop="productSpecificationName" :width="`${150 * $f}`" align="center" />
      <el-table-column label="税收编码" show-overflow-tooltip prop="taxCode" :width="`${255 * $f}`" align="center" />
      <el-table-column label="备注" show-overflow-tooltip prop="mark" :width="`${300 * $f}`" align="center" />
      <el-table-column v-if="sourceType != 3" label="操作" :width="`${140 * $f}`" align="center" fixed="right">
        <template slot-scope="{ row }">
          <el-button type="text" class="pub_button public_1EB398_btn" size="mini" @click="updateProductInfo(row)">编辑</el-button>
          <el-button v-if="sourceType == 1" type="text" class="pub_button public_F16363_btn" size="mini" @click="delBtnClick2(row)">删除</el-button>
        </template>
      </el-table-column>
      <template slot="empty">
        <PageEmptyData />
      </template>
    </el-table>
    <div v-if="sourceType != 3" class="mt20 fle">
      <el-button type="text" class="public_e0e2e7_btn pub_button" @click="handleClose">取消</el-button>
      <el-button type="text" class="public_confirm_btn pub_button" @click="submitBtnClick"> 提交 </el-button>
    </div>
    <!-- ====== 表格上方的筛选条件 end ======-->
    <!-- 删除提示 -->
    <deleteDialog :multiple-selection="multipleSelection" :visible="deleteDialogVisible" @close="closeDialog" @submit="confirmDelete" />
    <!-- 编辑产品数量 -->
    <PageDialog title="产品信息" :dialog-visible="chooseSalesmanDialogVisible" :width="`${$f * 600}px`" @close="closeDialog" @submit="confirmProductInfo">
      <el-form ref="ruleForm" :model="addParams" label-width="5.5rem" class="addOrder">
        <el-form-item v-if="sourceType == 1" label="业务员">
          <el-select v-model="addParams.companySaleName" placeholder="选择业务员" class="pub_select">
            <el-option v-for="item in companySaleList" :key="item.id" :label="item.companySaleName" :value="item.companySaleName"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <template #label>
            <span>
              <span>库存数量</span>
              <el-tooltip content="因库存时公司内共享，其他人可能也在同步出库，数量可能会实时减少" placement="top" effect="dark">
                <i class="el-icon-question" style="color:#606266;cursor:help;" />
              </el-tooltip>
            </span>
          </template>
          <el-input v-model="addParams.qtyNum" placeholder="请输入库存数量" class="pub_input" disabled />
        </el-form-item>
        <el-form-item label="出货数量">
          <el-input v-model="addParams.qty" placeholder="请不要超过库存数量" class="pub_input" :maxlength="5" type="number" />
        </el-form-item>
        <el-form-item v-if="sourceType == 1" label="出货单价">
          <el-input v-model="addParams.customerSinglePrice" placeholder="请输入出货单价" class="pub_input" :maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="订单备注">
          <el-input v-model="addParams.remark" placeholder="请输入备注" :rows="3" type="textarea" class="pub_input" />
        </el-form-item>
      </el-form>
    </PageDialog>
  </div>
</template>
<script>
import tableFun from '@/mixin/tableFun.js';
import { debounce } from '@/utils/debounce.js';
export default {
  mixins: [tableFun],
  data() {
    return {
      editCountDialogVisible: false, //编辑产品数量弹窗
      chooseSalesmanDialogVisible: false, //选择业务员弹窗
      params: {
        //列表请求参数
        purchaseInvoice: '2',
        purchaseInvoiceReceive: '2',
        dateInput: new Date().toISOString().split('T')[0],
        isHedging: '2' //1是对冲订单2是正常订单
      },
      addParams: { qty: '', customerSinglePrice: '', companySaleName: '', remark: '' },
      customerInfoTable: [], //客户信息数据
      productList: [], //商品信息
      companySaleList: [], //业务员列表
      dataListOrg: [],
      crumbsTitle: '',
      stockList: [], //库存列表
      sourceType: null //1：新增订单 2：编辑 3：查看详情
    };
  },
  computed: {
    userInfo() {
      return this.$store.state?.userInfo;
    }
  },
  created() {
    this.sourceType = this.$route.query.sourceType;
    switch (this.sourceType * 1) {
      case 1:
        this.crumbsTitle = '新增订单';
        break;
      case 2:
        this.crumbsTitle = '编辑订单';
        break;
      case 3:
        this.crumbsTitle = '订单信息';
        break;
      default:
        this.crumbsTitle = '订单信息';
        break;
    }
    this.getData();
  },
  methods: {
    // 获取库存列表
    async getStockList() {
      let res = await this.$api.get(this.$url.inventoryAll, this.params);
      this.stockList = res.rows;
    },
    //获取缓存中的数据
    getData() {
      this.params.isHedging = window.sessionStorage.getItem('orderType') || '2';
      // 从sessionStorage中恢复日期
      const savedDateInput = window.sessionStorage.getItem('dateInput');
      if (savedDateInput) {
        this.params.dateInput = savedDateInput;
      }
      let customerInfo = window.sessionStorage.getItem('customerInfo'); //客户信息
      if (customerInfo) {
        this.params = { ...this.params, ...JSON.parse(customerInfo) };
        this.customerInfoTable = [];
        this.customerInfoTable.push(JSON.parse(customerInfo));
      }
      let productList = window.sessionStorage.getItem('productList'); //商品信息
      if (productList) {
        productList = JSON.parse(productList);
        productList.forEach((val, index) => {
          val.index = index;
          val.inventoryId = val.id;
          if (!val.companySaleName) {
            val.companySaleName = this.userInfo.realName;
          }
        });
        if (!productList[productList.length - 1].qty) {
          this.updateProductInfo(productList[productList.length - 1]);
        }
      } else {
        productList = [];
      }
      this.productList = productList;
      if (this.sourceType != 1) {
        //查看编辑订单时调接口获取订单信息
        let orderInfo = JSON.parse(window.sessionStorage.getItem('orderInfo'));
        this.params = { ...this.params, ...orderInfo };
        this.getOrderInfo(); //获取订单信息
      }
    },
    //获取订单信息
    async getOrderInfo() {
      let res = await this.$api.get(this.$url.saleOrderInfo, { id: this.params.id });
      res.data = { ...res.data, researchGroupName: res.data.researchGroupName || '默认课题组' };
      this.params = { ...this.params, dateInput: res.data.dateInput, isHedging: res.data.isHedging };
      this.params.dateInput = res.data.dateInput;
      if (this.customerInfoTable.length === 0) {
        this.customerInfoTable.push(res.data);
      }
      // 先获取库存列表，确保stockList有数据
      await this.getStockList();
      let res2 = await this.$api.get(this.$url.relatedSaleOrders, { relatedId: res.data.relatedId });
      res2.data.forEach(item => {
        item.singlePrice = item.purchaseSinglePrice;
        // 根据productBatchNo匹配库存数量
        if (item.productBatchNo && this.stockList.length > 0) {
          const matchedStock = this.stockList.find(stock => stock.productBatchNo === item.productBatchNo);
          if (matchedStock && matchedStock.qty) {
            item.qtyNum = matchedStock.qty;
          }
        }
      });
      this.productList = [...this.productList, ...res2.data];
    },
    //关闭弹窗
    closeDialog() {
      this.selectedRow = null;
      this.deleteDialogVisible = false;
      this.chooseSalesmanDialogVisible = false;
      this.editCountDialogVisible = false;
      this.addParams = Object.assign({}, this.$options.data().addParams); //重置参数
      window.sessionStorage.setItem('productList', JSON.stringify(this.productList));
    },
    //选择订单类型
    selectedOrderType(type) {
      if (this.sourceType != 3) {
        this.params.isHedging = String(type);
        if (String(type) === '1') {
          this.customerInfoTable = [{ customerName: '对冲订单', researchGroupName: '对冲订单', customerPurchaserName: '对冲订单' }];
        } else {
          this.customerInfoTable = [];
        }
      }
    },
    //确认删除
    confirmDelete() {
      this.productList.splice(this.selectedRow.index, 1);
      window.sessionStorage.setItem('productList', JSON.stringify(this.productList));
      let productList = window.sessionStorage.getItem('productList'); //商品信息
      if (productList) {
        productList = JSON.parse(productList);
        productList.forEach((val, index) => {
          val.index = index;
          val.inventoryId = val.id;
          val.qtyNum = val.qty;
          val.qty = null;
        });
      } else {
        productList = [];
      }
      this.productList = productList;
      this.closeDialog();
    },
    //编辑产品数量
    editorderCount(val) {
      this.selectedRow = JSON.parse(JSON.stringify(val));
      this.addParams.qty = val.qty;
      this.showDilogBtn('editCountDialogVisible');
    },
    //订单类型说明弹框
    orderTypePopup(val) {
      this.showDilogBtn('questionDialogVisible');
    },
    //选择业务员
    async updateProductInfo(val) {
      this.addParams = { ...JSON.parse(JSON.stringify(val)) };
      let res = await this.$api.get(this.$url.companySale, { companyId: val.companyId });
      this.selectedRow = JSON.parse(JSON.stringify(val));
      if (res?.data) {
        res.data.forEach(el => {
          el.companySaleName = el.companySaleName ? el.companySaleName : this.userInfo.realName || this.userInfo.roleName;
        });
        this.companySaleList = res.data || [];
        this.addParams.companySaleName = val.companySaleName;
      } else {
        this.selectedRow.companySaleName = '暂不选择';
        this.productList.splice(this.selectedRow.index, 1, this.selectedRow);
        this.$message.warning('公司名下没有员工，暂不选择');
      }
      this.showDilogBtn('chooseSalesmanDialogVisible');
    },
    //确认添加产品数量
    confirmProductInfo() {
      const { qty, companySaleName, customerSinglePrice, remark } = this.addParams;
      if (!companySaleName && this.sourceType == 1) {
        return this.$message.warning('请选择业务员');
      }
      if (!qty || qty < 1) {
        return this.$message.warning('请输入正确的产品数量');
      }
      if (!customerSinglePrice && this.sourceType == 1) {
        return this.$message.warning('请输入出货单价');
      }
      if (this.sourceType == 1) {
        this.selectedRow.qty = qty;
        this.selectedRow.companySaleName = companySaleName;
      }
      this.selectedRow.customerSinglePrice = customerSinglePrice;
      this.selectedRow.remark = remark;
      this.productList.splice(this.selectedRow.index, 1, this.selectedRow);
      this.$message.success('产品信息更新成功');
      this.closeDialog();
    },
    //页面跳转
    goPage(pageUrl) {
      window.sessionStorage.setItem('orderType', this.params.isHedging);
      window.sessionStorage.setItem('dateInput', this.params.dateInput);
      if (this.productList.length > 0) {
        window.sessionStorage.setItem('productList', JSON.stringify(this.productList));
      }
      if (this.customerInfoTable.length > 0) {
        window.sessionStorage.setItem('customerInfo', JSON.stringify(this.customerInfoTable[0]));
      }
      this.$router.push({ path: '/' + pageUrl, query: { activeIndex: '1', sourceType: this.sourceType } });
    },
    handleClose() {
      this.goPage('layout/orderManagement');
    },
    //删除重新写删除
    delBtnClick2(val) {
      this.selectedRow = JSON.parse(JSON.stringify(val));
      this.showDilogBtn('deleteDialogVisible');
    },
    //提交订单
    submitBtnClick: debounce(async function() {
      const { customerName, dateInput } = this.params;
      if (!dateInput) {
        return this.$message.warning('请选择订单日期');
      }
      if (!customerName) {
        return this.$message.warning('请选择客户');
      }
      if (this.productList.length === 0) {
        return this.$message.warning('请选择商品');
      }
      let showFlag = false;
      this.productList.forEach((el, idx) => {
        el.qty = Number(el.qty);
        el.customerSinglePrice = Number(el.customerSinglePrice);
        if (!el.companySaleName && !showFlag) {
          showFlag = true;
          this.$message.warning(`请先选择商品信息序号(${idx + 1})的业务员`);
        } else if (Number(el.customerSinglePrice) < 0 && !showFlag) {
          showFlag = true;
          this.$message.warning(`商品信息序号(${idx + 1})的出货单价不能小于0`);
        } else if ((!el.qty || el.qty == 0) && !showFlag) {
          showFlag = true;
          this.$message.warning(`请先输入商品信息序号(${idx + 1})的产品数量`);
        } else if (el.customerSinglePrice !== 0 && !el.customerSinglePrice && !showFlag) {
          showFlag = true;
          this.$message.warning(`请先输入商品信息序号(${idx + 1})的出货单价`);
        }
        el.customerTotalPrice = el.customerSinglePrice * el.qty;
        el.purchaseSinglePrice = el.singlePrice;
        el.purchaseTotalPrice = el.purchaseSinglePrice * el.qty;
        el.grossProfit = el.customerTotalPrice - el.purchaseTotalPrice;
        if (this.params.isHedging === '1') {
          el.customerSinglePrice = el.singlePrice;
          el.customerTotalPrice = Number(el.singlePrice) * Number(el.qty);
        }
      });
      if (!showFlag) {
        // 直接使用用户选择的日期，不做额外转换
        this.params = { ...this.params, addList: this.productList, purchaseInvoice: '2', purchaseInvoiceReceive: '2', isHedging: this.params.isHedging };
        let res = await this.$api.post(this.params.id ? this.$url.saleOrderUpdate : this.$url.addSaleOrder, this.params);
        if (res.code === 200) {
          this.$message.success(this.params.id ? '更新成功' : '新增成功');
          window.sessionStorage.clear();
          this.handleClose();
        }
      }
    }, 500)
  }
};
</script>
<style lang="less" scoped>
.table_filter_search {
  width: 100%;
}
.pub_table {
  height: auto;
}
.table_filter_title {
  font-size: 16px;
  color: #0a0b0d;
}
.orderType {
  cursor: pointer;
}
.customerInfo {
  li {
    span {
      font-size: 14px;
      color: #333;
      & + span {
        color: #606266;
      }
    }
    span:first-child {
      width: 100px;
      text-align: left;
      margin-right: 10px;
    }
    & + li {
      margin-left: 30px;
    }
  }
}
</style>
